package com.mohe.shanpao.netty;

import java.math.BigInteger;
import java.util.List;

import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.ByteToMessageDecoder;

public class BigIntegerDecoder extends ByteToMessageDecoder {

	@Override
	protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) throws Exception {
		//分隔符+长度
		if(in.readableBytes() < 5)
		{
			return;
		}
		
		in.markReaderIndex();
		
		int magic = in.readInt();
		
		if('F' == magic)
		{
			int length = in.readInt();
			if(in.readableBytes() < length)
			{
				in.resetReaderIndex();
				return;
			}
			
			byte[] decoded = new byte[length];
			in.readBytes(decoded);
			
			out.add(new BigInteger(decoded));
			
		}
	}

}
